import os
import platform
import glob

def ensure_dir_exists(dir_path):
    """
    确保目录存在，如果不存在则创建
    """
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, exist_ok=True)
        print(f"创建目录: {dir_path}")
    return dir_path


def get_absolute_path(path):
    """
    获取绝对路径
    """
    if not path:
        return None
    if os.path.isabs(path):
        return path
    else:
        return os.path.abspath(path)


def get_file_extension(file_path):
    """
    获取文件扩展名（小写）
    """
    _, ext = os.path.splitext(file_path)
    return ext.lower()


def is_image_file(file_path):
    """
    检查是否为图像文件
    """
    image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
    return get_file_extension(file_path) in image_extensions


def is_video_file(file_path):
    """
    检查是否为视频文件
    """
    video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm']
    return get_file_extension(file_path) in video_extensions


def get_files_in_directory(dir_path, extensions=None, recursive=True):
    """
    获取目录下所有指定扩展名的文件
    
    Args:
        dir_path: 目录路径
        extensions: 扩展名列表，如['.jpg', '.png']，如果为None则获取所有文件
        recursive: 是否递归搜索子目录
        
    Returns:
        文件路径列表
    """
    if not os.path.exists(dir_path):
        print(f"目录不存在: {dir_path}")
        return []
    
    files = []
    pattern = '**/*' if recursive else '*'
    
    for file_path in glob.glob(os.path.join(dir_path, pattern), recursive=recursive):
        if os.path.isfile(file_path):
            if extensions is None or get_file_extension(file_path) in extensions:
                files.append(file_path)
    
    return files


def get_image_files_in_directory(dir_path, recursive=True):
    """
    获取目录下所有图像文件
    """
    image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp']
    return get_files_in_directory(dir_path, image_extensions, recursive)


def get_video_files_in_directory(dir_path, recursive=True):
    """
    获取目录下所有视频文件
    """
    video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm']
    return get_files_in_directory(dir_path, video_extensions, recursive)


def get_unique_filename(base_dir, base_name, extension):
    """
    获取唯一的文件名，避免覆盖现有文件
    """
    counter = 1
    filename = f"{base_name}{extension}"
    full_path = os.path.join(base_dir, filename)
    
    while os.path.exists(full_path):
        filename = f"{base_name}_{counter}{extension}"
        full_path = os.path.join(base_dir, filename)
        counter += 1
    
    return full_path


def join_paths(*paths):
    """
    安全地连接路径，处理不同操作系统的路径分隔符
    """
    return os.path.join(*paths)


def get_system_type():
    """
    获取当前操作系统类型
    """
    return platform.system().lower()


def get_default_cache_dir():
    """
    获取默认的缓存目录
    """
    system = get_system_type()
    if system == 'windows':
        return os.path.join(os.environ.get('APPDATA', os.path.expanduser('~')), 'minicpm-v', 'cache')
    else:
        return os.path.join(os.path.expanduser('~'), '.cache', 'minicpm-v')


def clean_path(path):
    """
    清理路径，规范化路径分隔符
    """
    if not path:
        return path
    return os.path.normpath(path)